import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login'
import Layout from '@/views/layout'
import NotFound from '@/views/404'
import Search from '@/views/search'
import store from '@/store'

// 二级路由
import Home from '@/views/layout/home'
import QA from '@/views/layout/qa'
import Video from '@/views/layout/video'
import User from '@/views/layout/user'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: Home
      },
      {
        path: 'qa',
        component: QA
      }, {
        path: 'video',
        component: Video
      }, {
        path: 'user',
        component: User
      }
    ]

  },
  {
    path: '/login',
    component: Login

  },
  {
    path: '/search',
    component: Search

  },
  {
    path: '*',
    component: NotFound

  }
]

const router = new VueRouter({
  routes
})

// 定义
const loginURL = ['/user']
// 全局导航守卫==> 用户没等登录，就跳转到登录
router.beforeEach((to, form, next) => {
  const token = store.state.user.token.token
  // 先判断有没有token，有就正常跳转
  // 没有token，再判断要跳转的页面是否为个人中心，是就拦截，不是就放行
  if (token) {
    next()
  } else {
    if (loginURL.some(item => item === to.path)) {
      // next('/logign')  有导航故障
      router.push('login')
    } else {
      next()
    }
  }
})

export default router
